package com.mall.controller;

import com.mall.pojo.vo.CartItemVO;
import com.mall.service.CartService;
import com.mall.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车控制器
 */
@RestController
@RequestMapping("/member/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 获取购物车列表
     */
    @GetMapping
    public Result<List<CartItemVO>> getCartList() {
        List<CartItemVO> cartList = cartService.getCartList();
        return Result.success(cartList);
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping
    public Result<Boolean> addToCart(@RequestBody CartItemVO cartItem) {
        boolean result = cartService.addToCart(cartItem);
        return Result.success(result);
    }

    /**
     * 删除购物车商品
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteFromCart(@PathVariable Long id) {
        try {
            boolean result = cartService.deleteCartItem(id);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("删除购物车商品失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除购物车商品时发生错误: " + e.getMessage());
        }
    }

    /**
     * 更新购物车商品
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateCart(@PathVariable Long id, @RequestBody CartItemVO cartItem) {
        try {
            boolean result = cartService.updateCartItem(id, cartItem);
            if (result) {
                return Result.success(true);
            } else {
                return Result.error("更新购物车商品失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新购物车商品时发生错误: " + e.getMessage());
        }
    }
} 